package com.java.simple.study.jvm.memstruct.directmemory;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author zhoujunlin
 * @date 2021/12/14
 * @desc io与nio直接内存
 **/
public class Demo4_1 {
    // 大mp4  1.2G
    private static final String FROM = "D:\\BaiduNetdiskDownload\\源码五班\\02 源码分析--spring概述\\5285890807702856103_源码分析--spring概述.mp4";
    private static final String TO = "D:\\a.mp4";
    private static final int _1M = 1024 * 1024;

    public static void main(String[] args) {
        io();  // 耗时多2570ms
        nio();  // 耗时少1531
    }

    private static void nio() {
        long currentTimeMillis = System.currentTimeMillis();
        try (FileChannel from = new FileInputStream(FROM).getChannel();
             FileChannel to = new FileOutputStream(TO).getChannel();
        ) {
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(_1M);
            while (true) {
                int read = from.read(byteBuffer);
                if (read == -1) {
                    break;
                }
                byteBuffer.flip();
                to.write(byteBuffer);
                byteBuffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("nio用时：" + (System.currentTimeMillis() - currentTimeMillis));
        }
    }


    private static void io() {
        long currentTimeMillis = System.currentTimeMillis();
        try (FileInputStream from = new FileInputStream(FROM);
             FileOutputStream to = new FileOutputStream(TO);
        ) {
            byte[] bytes = new byte[_1M];
            while (true) {
                int read = from.read(bytes);
                if (read == -1) {
                    break;
                }
                to.write(bytes, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("io用时：" + (System.currentTimeMillis() - currentTimeMillis));
        }
    }

}
